package main

import (
	"fmt"
	"time"
	"os"
	"bufio"
	"io"
	"strings"
	"net/http"
)

type LogProcess struct {
	rc chan []byte
	wc chan string
	//path string
	//dsn string
	read Reader
	write Writer
}

type Reader interface {
	Read(rc chan []byte)
}
type Writer interface {
	Write(wc chan string)
}
type ReadFromFile struct {
	path string
}
type WriteToInfluxDb struct {
	dsn string
}
//func (l *LogProcess) WriteToInfluxDb() {
//	fmt.Println(<-l.wc)
//}
func (r *WriteToInfluxDb) Write(wc chan string)  {
	//fmt.Println(<-wc)
	for v := range wc {
		fmt.Println(v)
	}
}
//func (l *LogProcess) ReadFromLine() {
//	line := "mes"
//	l.rc <-line
//}
func (r *ReadFromFile) Read(rc chan []byte) {
	f,err := os.Open(r.path)
	defer f.Close()
	if err != nil{
		panic(fmt.Sprintf("open file err :%s",err.Error()))
	}
	//f.Seek(0,2)
	rd := bufio.NewReader(f)
	for {
		line,err := rd.ReadBytes('\n')
		if err == io.EOF {
			time.Sleep(500*time.Microsecond)
			continue
		}else if err != nil{
			panic(fmt.Sprintf("readbytes err :%s",err.Error()))
		}
		fmt.Println("test...")
		//line := "mes"
		rc <-line[:len(line)-1]
	}
}

func (l *LogProcess) Process() {
	for v := range l.rc {
		l.wc <-strings.ToUpper(string(v))
	}
	rand
	//data := <-l.rc
	//l.wc <-strings.ToUpper(string(data))
}
func main() {
	//1
	//lp := &LogProcess{
	//	rc : make(chan string),
	//	wc : make(chan string),
	//	path : "tmp/access.log",
	//	dsn : "username&password..",
	//}
	//go lp.ReadFromLine() // sys auto (*lp)
	//go lp.Process()
	//go lp.WriteToInfluxDb()
	rand
	//2
	r := &ReadFromFile{
		path : "./access.log",
	}
	w := &WriteToInfluxDb{
		dsn : "username&password.",
	}
	lp := &LogProcess{
		rc :make(chan []byte),
		wc :make(chan string),
		read:r,
		write:w,
	}
	go lp.read.Read(lp.rc)
	go lp.Process()
	go lp.write.Write(lp.wc)

	time.Sleep(30*time.Second)
	//fmt.Println(time.Second)
}
